// SPDX-License-Identifier: Apache-2.0
/* -*- P4_16 -*- */
#include <core.p4>
#include <v1model.p4>

// cpu端口号
#define CPU_PORT 510
// conga报文中ce字段所占位数
#define CE_TYPE_LENGTH 32

#define LBTAG_TYPE_LENGTH 8
#define SWITCH_OUTPUT_NUMBER 6 // 交换机端口的数量
#define LEAF_SWITCH_NUMBER 3 // 叶交换机的数量
#define PATH_NUMBER 4 // 从源IP地址到目的IP地址包含的路径数量
#define HOST_NUMBER 2 // 每台交换机下面连接的主机的数量

#define SUB_FACTOR 2// 用来更新DRE模块的x寄存器
#define FLOW_ENTRY_EXPIRE_TIME 500000 // 表项过期时间，单位为微秒
#define UPDATE_XREG_TIME 500000

const bit<16> TYPE_IPV4 = 0x0800;
const bit<16> TYPE_CONGA = 0x0810;
const bit<8> TYPE_TCP =0x06;
const bit<8> TYPE_UDP =0x11;

const bit<32> FLOWTABLE_SIZE = 65536; 
const bit<32> CG_REG_SIZE = 24; // 拥塞信息寄存器的大小，保存的是到目的叶交换机各路径的拥塞信息


/*************************************************************************
*********************** H E A D E R S  ***********************************
*************************************************************************/

typedef bit<9>  egressSpec_t;
typedef bit<48> macAddr_t;
typedef bit<32> ip4Addr_t;
typedef bit<16> PortIdToController_t; // 发送packet-in报文给控制器时，packet-in报文的输入端口类型

typedef bit<LBTAG_TYPE_LENGTH> lbTag_t; // conga报文LBTag字段类型
typedef bit<CE_TYPE_LENGTH> ce_t; // 拥塞程度类型
typedef bit<(LBTAG_TYPE_LENGTH+1+1)> flowTableValue_t; // 流表中value值的类型
typedef bit<(LBTAG_TYPE_LENGTH+CE_TYPE_LENGTH)> congestionValue_t; 


header ethernet_h {
    macAddr_t dstAddr;
    macAddr_t srcAddr;
    bit<16>   etherType;
}

header conga_h{
    ip4Addr_t srcAddr;
    ip4Addr_t dstAddr;
    bit<16> hash;
    bit<8> direction; // conga报文的传送方向
    lbTag_t LBTag;
    ce_t CE;
}

header ipv4_h {
    bit<4>    version;
    bit<4>    ihl;
    bit<8>    diffserv;
    bit<16>   totalLen;
    bit<16>   identification;
    bit<3>    flags;
    bit<13>   fragOffset;
    bit<8>    ttl;
    bit<8>    protocol;
    bit<16>   hdrChecksum;
    ip4Addr_t srcAddr;
    ip4Addr_t dstAddr;
}

header tcp_h {
    bit<16> srcPort;
    bit<16> dstPort;
    bit<32> seqNo;
    bit<32> ackNo;
    bit<4>  dataOffset;
    bit<3>  res;
    bit<3>  ecn;
    bit<6>  ctrl;
    bit<16> window;
    bit<16> checksum;
    bit<16> urgentPtr;
}

header udp_h {
    bit<16> src_port;  // Source port
    bit<16> dst_port;  // Destination port
    bit<16> length;    // Length of UDP packet
    bit<16> checksum;  // Checksum
}

// 和控制层进行交互的信息格式
enum bit<8> ControllerOpcode_e {
    NO_OP          = 0,
    READ_CONGESTION_REG  = 1,
    WRITE_CONGESTION_REG = 2,
    READ_FLOWTABLE_REG =3,
    RESET_FLOWTABLE_REG = 4,
    WRITE_FLOWTABLE_REG = 5,
    GENERATE_CONGA = 6,
    UPDATE_XREG = 7
}

enum bit<8> PuntReason_e {
    UNRECOGNIZED_OPCODE = 1,
    OPERATION_RESPONSE  = 2,
    ACTIVE_REQUEST = 3,
}

@controller_header("packet_in")
header packet_in_header_h {
    PortIdToController_t input_port;
    PuntReason_e         punt_reason;
    ControllerOpcode_e   opcode;
    bit<32> operand0;
    bit<32> operand1;
    bit<32> operand2;
    bit<32> operand3;
    bit<32> operand4;
}

@controller_header("packet_out")
header packet_out_header_h {
    PortIdToController_t input_port;
    ControllerOpcode_e   opcode;
    bit<32> operand0;
    bit<32> operand1;
    bit<32> operand2;
    bit<32> operand3;
    bit<32> operand4;
}

struct metadata{
    egressSpec_t outPut;
    bit<32> cg_rg_index;
    lbTag_t expireTag;
    ip4Addr_t addr;
}

struct headers {
    packet_in_header_h packet_in;
    packet_out_header_h packet_out;
    ethernet_h ethernet;
    conga_h conga;
    ipv4_h ipv4;
    tcp_h tcp;
    udp_h udp;
}

/*************************************************************************
*********************** P A R S E R  ***********************************
*************************************************************************/

parser MyParser(packet_in packet,
                out headers hdr,
                inout metadata meta,
                inout standard_metadata_t standard_metadata) {

    state start {
        transition parse_packet;
    }

    state parse_packet{

        transition select(standard_metadata.ingress_port){
            // modify: 
            CPU_PORT: parse_packet_out_of_controller;
            default: parse_ethernet;
        }
    }

    state parse_ethernet{
        
        packet.extract(hdr.ethernet);
        transition select(hdr.ethernet.etherType){

            TYPE_IPV4: parse_ipv4;
            TYPE_CONGA: parse_conga;
            default: accept;
        }
    }

    state parse_packet_out_of_controller{
        packet.extract(hdr.packet_out);
        transition accept;
    }

    state parse_ipv4{
        packet.extract(hdr.ipv4);
        transition select(hdr.ipv4.protocol){
            TYPE_TCP: parse_tcp;
            TYPE_UDP: parse_udp;
            default: accept;
        }
    }
    state parse_conga{
        packet.extract(hdr.conga);
        transition accept;
    }
    state parse_tcp{
        packet.extract(hdr.tcp);
        transition accept;
    }
    state parse_udp{
        packet.extract(hdr.udp);
        transition accept;
    }
}


/*************************************************************************
************   C H E C K S U M    V E R I F I C A T I O N   *************
*************************************************************************/

control MyVerifyChecksum(inout headers hdr, inout metadata meta) {
    apply { 
        
    }
}

/*************************************************************************
**************  I N G R E S S   P R O C E S S I N G   *******************
*************************************************************************/

control MyIngress(inout headers hdr,
                  inout metadata meta,
                  inout standard_metadata_t standard_metadata) {
    
    // 转发流表，根据5元组hash值进行转发，分别对应ce值，valid值和age值
    register<flowTableValue_t>(FLOWTABLE_SIZE) flow_table;
    register<bit<48>> (FLOWTABLE_SIZE) flow_ingress_table; 

    // 记录到目的IP地址的拥塞信息
    register<congestionValue_t>(CG_REG_SIZE) congestion_to_leaf_register;
    register<bit<48>>(CG_REG_SIZE) cg_entry_update_time_register;
    // 记录流的到达时刻，用于更新流表

    // todo: 记录已收到的回传conga报文的数量，其中index对应的是不同目的IP地址对应的下标，由控制器决定
    register<bit<32>> ((bit<32>) LEAF_SWITCH_NUMBER) probed_path_number_register;

    register<bit<1>> ((bit<32>) 2) signal_register;

    // 下标0对应的是流表项的过期时间，1对应的是congestion_to_leaf表项过期的时间
    register <bit<48>> ((bit<32>) 2) expire_time_register;

    action drop() {
        mark_to_drop(standard_metadata);
    }

    action send_to_controller_with_details(
        PuntReason_e       punt_reason,
        ControllerOpcode_e opcode,
        bit<32> operand0,
        bit<32> operand1,
        bit<32> operand2,
        bit<32> operand3,
        bit<32> operand4)
    {
        standard_metadata.egress_spec = CPU_PORT;
        hdr.packet_in.setValid();
        hdr.packet_in.input_port = (PortIdToController_t) standard_metadata.ingress_port;
        hdr.packet_in.opcode = opcode;
        hdr.packet_in.punt_reason = punt_reason;
        hdr.packet_in.operand0 = operand0;
        hdr.packet_in.operand1 = operand1;
        hdr.packet_in.operand2 = operand2;
        hdr.packet_in.operand3 = operand3;
        hdr.packet_in.operand4 = operand4;
    }
    
    action update_ipv4_fields(){
        hdr.ipv4.ttl=hdr.ipv4.ttl-1;
    }

    action set_mac(macAddr_t dstMac){
        hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
        hdr.ethernet.dstAddr = dstMac;
    }

    table mac_exact{
        key = {
            standard_metadata.egress_spec: exact;
        }
        actions={
            set_mac;
            NoAction;
        }
        default_action = NoAction;
        size = 30;
    }

    action ipv4_forward(egressSpec_t port) {
        standard_metadata.egress_spec=port;
        update_ipv4_fields();
    }

    table ipv4_local_lpm {
        key = {
            hdr.ipv4.dstAddr: lpm;
        }
        actions = {
            ipv4_forward;
            drop;
            NoAction;
        }
        size = 1024;
        default_action = NoAction();
    }

    table ipv4_diffserv_lpm{
        key={
            hdr.ipv4.dstAddr: lpm;
            hdr.ipv4.diffserv:exact;
        }
        actions={
            ipv4_forward;
            NoAction;
        }
        size=100;
        default_action = NoAction;
    }

    action conga_forward(bit<9> port){
        standard_metadata.egress_spec=port;
    }

    table conga_lpm{
        key={
            hdr.conga.dstAddr: lpm;
            hdr.conga.LBTag: exact;
        }
        actions={
            conga_forward;
            NoAction;
        }
        size=1024;
        default_action=NoAction;
    }

    action return_conga(){
        if(hdr.conga.isValid()){
            // 正常情况下为真
            hdr.conga.direction = 1; // 设置报文传送方向
        }
        standard_metadata.egress_spec=standard_metadata.ingress_port;
    }

    table conga_dst{
        key={
            hdr.conga.dstAddr: lpm;
        }
        actions={
            return_conga;
            NoAction;
        }
        default_action=NoAction;
        size=10;
    }

    action conga_backforward(bit<9> port){
        standard_metadata.egress_spec=port;
    }

    table conga_back{
        key={
            hdr.conga.srcAddr: lpm;
        }
        actions={
            conga_backforward;
            NoAction;
        }
        size=8;
        default_action=NoAction();
    }

    action get_index(bit<32> index){
        meta.cg_rg_index = index;
    }

    table congestion_to_leaf_lpm{

        key={
            meta.addr: lpm;
        }
        actions={
            get_index;
            NoAction;
        }
        size  = 100;
        default_action = NoAction;
    }

    action update_congestion_to_leaf(){
        // congestion_to_leaf_register.write((bit<32>) hdr.conga.LBTag - (bit<32>) 1 + index , hdr.conga.CE);
        // conga报文主机端时延RTT大概在10毫秒左右
        congestionValue_t value;
        congestion_to_leaf_register.read(value, meta.cg_rg_index);
        ce_t ce = value [CE_TYPE_LENGTH-1:0];
        lbTag_t tag = value [CE_TYPE_LENGTH+LBTAG_TYPE_LENGTH-1 : CE_TYPE_LENGTH];

        bit<48> cg_entry_expire_time;
        expire_time_register.read(cg_entry_expire_time, (bit<32>) 1);

        bit<48> cg_entry_update_time;
        cg_entry_update_time_register.read(cg_entry_update_time, meta.cg_rg_index);

        if(hdr.conga.CE < ce || standard_metadata.ingress_global_timestamp - cg_entry_update_time > cg_entry_expire_time){
            meta.expireTag = tag;
            congestion_to_leaf_register.write(meta.cg_rg_index, hdr.conga.LBTag++hdr.conga.CE);
            cg_entry_update_time_register.write(meta.cg_rg_index,standard_metadata.ingress_global_timestamp);
        }else{
            meta.expireTag = (lbTag_t) 255;
        }
        log_msg("conga packet from {} to {} and probe lbtag = {} with CE value = {}",
            {hdr.conga.srcAddr,hdr.conga.dstAddr,hdr.conga.LBTag,hdr.conga.CE});
    }

    table conga_src{
        key={
            hdr.conga.srcAddr: lpm;
        }

        actions={
            update_congestion_to_leaf;
            NoAction;
        }

        size=1024;
        default_action=NoAction;
    }

    action request_conga(bit<8> index){
        bit<32> probed_number;
        probed_path_number_register.read(probed_number,(bit<32>) index);
        probed_number = probed_number + 1;
        if(meta.expireTag < 255){
            probed_number = 0;
            probed_path_number_register.write((bit<32>) index, probed_number);
            send_to_controller_with_details(
                PuntReason_e.ACTIVE_REQUEST,
                ControllerOpcode_e.GENERATE_CONGA,
                hdr.conga.srcAddr,
                hdr.conga.dstAddr,
                (bit<32>)meta.expireTag,
                0,
                0
            );
            log_msg("request controller to generate conga  src is {}, dst is {}",{hdr.conga.srcAddr,hdr.conga.dstAddr});
        }else{
            probed_path_number_register.write((bit<32>) index, probed_number);
            drop();
        }
        
    }

    table conga_request_lpm{
        key={
            hdr.conga.dstAddr: lpm;
        }
        actions={
            request_conga;
            NoAction;
        }
        size = 100;
        default_action = NoAction;
    }

    action is_leaf_switch(){

    }

    table leaf_switch_lpm{
        key={
            hdr.ipv4.srcAddr: lpm;
        }
        actions ={
            is_leaf_switch;
            NoAction;
        }
        default_action = NoAction;
        size = 10;
    }

    apply {
        if(hdr.ipv4.isValid()){
            meta.addr = hdr.ipv4.dstAddr;
        }
        if(hdr.conga.isValid()){
            meta.addr = hdr.conga.dstAddr;
        }
        congestion_to_leaf_lpm.apply();

        if( hdr.ipv4.isValid() ){
            if(ipv4_local_lpm.apply().miss){
                // 根据服务类型字段进行转发
                switch(leaf_switch_lpm.apply().action_run){
                    is_leaf_switch:{
                        bit<16> hash_value;
                        if(hdr.udp.isValid()){
                            hash(hash_value,
                                HashAlgorithm.crc16,
                                (bit<16>)0,
                                {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.ipv4.protocol,hdr.udp.src_port,hdr.udp.dst_port},
                                (bit<16>)65535);
                        }else if(hdr.tcp.isValid()){
                            hash(hash_value,
                                HashAlgorithm.crc16,
                                (bit<16>)0,
                                {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.ipv4.protocol,hdr.tcp.srcPort,hdr.tcp.dstPort},
                                (bit<16>)65535);
                        }else{
                            hash(hash_value,
                            HashAlgorithm.crc16,
                            (bit<16>)0,
                            {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.ipv4.protocol},
                            (bit<16>)65535);
                        }
                        log_msg("new flowlet's hash is {}",{hash_value});
                        flowTableValue_t value;
                        flow_table.read(value,(bit<32>)hash_value);
                        bit<48> ingress_time;
                        flow_ingress_table.read(ingress_time,(bit<32>)hash_value);
                        bit<48> flow_entry_expire_time;
                        expire_time_register.read(flow_entry_expire_time,(bit<32>) 0);
                        if(value==0 || value[1:1]==0 || standard_metadata.ingress_global_timestamp - ingress_time > flow_entry_expire_time){ // 有效位为0
                            log_msg("a new flowlet appears, decide to forward this flow to .....");
                            // 查找congestion_to_leaf寄存器确定最小拥塞路径
                            congestionValue_t cg_value;
                            congestion_to_leaf_register.read(cg_value, meta.cg_rg_index);
                            hdr.ipv4.diffserv = (bit<8>)cg_value[CE_TYPE_LENGTH+LBTAG_TYPE_LENGTH-1:CE_TYPE_LENGTH];
                            flow_table.write((bit<32>)hash_value,(lbTag_t)cg_value[CE_TYPE_LENGTH+LBTAG_TYPE_LENGTH-1:CE_TYPE_LENGTH]++1w0b1++1w0b1);
                            flow_ingress_table.write((bit<32>)hash_value, standard_metadata.ingress_global_timestamp);
                        }else{
                            // 转发数据包
                            hdr.ipv4.diffserv = (lbTag_t)value[LBTAG_TYPE_LENGTH-1:2];
                        }
                    }
                }
                ipv4_diffserv_lpm.apply();
            }
            // 设置mac地址
            mac_exact.apply();
        }else{
            // 处理packetOut报文
            if(hdr.packet_out.isValid()){
                switch(hdr.packet_out.opcode){
                    ControllerOpcode_e.GENERATE_CONGA:{
                        // 转化为conga报文，并且完成转发
                        hdr.ethernet.setValid();
                        hdr.conga.setValid();
                        hdr.ethernet.etherType=TYPE_CONGA;
                        hdr.conga.srcAddr=hdr.packet_out.operand0;
                        hdr.conga.dstAddr=hdr.packet_out.operand1;
                        hdr.conga.hash=(bit<16>)hdr.packet_out.operand2;
                        hdr.conga.LBTag=(lbTag_t)hdr.packet_out.operand3;
                        egressSpec_t port = (egressSpec_t)hdr.packet_out.operand4;
                        hdr.conga.CE=0;
                        hdr.conga.direction = 0;
                        hdr.packet_out.setInvalid();
                        log_msg("receiving conga packet with dstAddr = {}, hash = {}, output port = {}",
                        {hdr.conga.dstAddr,hdr.conga.hash,port});
                        // 转发conga报文
                        standard_metadata.egress_spec=port;
                    }
                            
                    // todo更新对应寄存器的值
                    ControllerOpcode_e.WRITE_CONGESTION_REG:{
                        // 根据dstAddr查找表path2Index_exact得到index，更新congestion_to_leaf
                        // todo: 修改congestion_to_leaf的接口
                        drop();
                    }
                    ControllerOpcode_e.WRITE_FLOWTABLE_REG:{

                    }
                    ControllerOpcode_e.UPDATE_XREG:{
                        log_msg("receiving update x register signal");
                        signal_register.write((bit<32>) 1, (bit<1>) 1);
                        drop();
                    }
                    ControllerOpcode_e.RESET_FLOWTABLE_REG:{
                        flow_table.write((bit<32>)hdr.packet_out.operand0,(flowTableValue_t)0);
                        drop();
                    }
                }
            }else{
                if(hdr.conga.isValid()){
                    if(hdr.conga.direction==0){
                        conga_lpm.apply(); // 转发conga报文
                        // 判断是否到达目的交换机，到达目的交换机按照原路将报文返回回去，同时更新寄存器的值
                        conga_dst.apply();
                    }else{
                        // 完成报文回传
                        conga_back.apply();
                        // 到达源交换机更新congestion_to_leaf和流表
                        conga_src.apply();
                        // 判断是否需要发送请求给控制器发送conga探测报文
                        conga_request_lpm.apply();
                    }
                }
            }
        }
        meta.outPut=standard_metadata.egress_spec;
    }
}

/*************************************************************************
****************  E G R E S S   P R O C E S S I N G   *******************
*************************************************************************/

control MyEgress(inout headers hdr,
                 inout metadata meta,
                 inout standard_metadata_t standard_metadata) {
    

    counter(
        (bit<32>)SWITCH_OUTPUT_NUMBER,
        CounterType.bytes) packets_counter;

    // 定义register实现DRE模块
    // change：使用register寄存器记录交换机各个端口输出的报文数量
    register<ce_t>(SWITCH_OUTPUT_NUMBER) x_register;

    // 用于输出日志：记录上一次报文的输出端口号
    register <egressSpec_t> (1) last_port_register;
    register <bit<32>> (SWITCH_OUTPUT_NUMBER) last_port_output_packets_number_register;

    // 用于更新 x_register
    register <bit<48>>(1) egress_stamp_register;

    // x_register存储信息更新时间
    register <bit<48>>(1) x_register_expire_time_register;

    apply {

        if (hdr.conga.isValid() && hdr.conga.direction == 0){
            bit<32> value;
            x_register.read(value,(bit<32>) meta.outPut - (bit<32>) 1);
            if(value > hdr.conga.CE){
                hdr.conga.CE = value;
            }
        }else if(hdr.ipv4.isValid()){
            bit<32> value;
            bit<32> register_index = (bit<32>) meta.outPut - (bit<32>) 1;
            packets_counter.count(register_index); // 更新counter的值
            x_register.read(value,register_index);
            value = value + standard_metadata.packet_length;
            x_register.write(register_index,value);
            egressSpec_t last_port;
            last_port_register.read(last_port, (bit<32>)0);
            bit<32> numbers;
            last_port_output_packets_number_register.read(numbers,register_index);
            if(meta.outPut == last_port){
                last_port_output_packets_number_register.write(register_index, numbers + standard_metadata.packet_length);
            }else{
                last_port_register.write((bit<32>) 0,meta.outPut);
                last_port_output_packets_number_register.write(register_index,standard_metadata.packet_length);
                log_msg("ipv4 packet output port is {} and forwards {} bytes",{last_port,numbers});
            }
        }

        bit<48> timestamp;
        egress_stamp_register.read(timestamp, (bit<32>) 0);
        bit<48> x_register_expire_time;
        x_register_expire_time_register.read(x_register_expire_time, (bit<32>) 0);
        if(standard_metadata.egress_global_timestamp - timestamp > x_register_expire_time){
            log_msg("at clock {} update x_register and last update time is {}",{standard_metadata.egress_global_timestamp,timestamp});
            egress_stamp_register.write((bit<32>) 0,standard_metadata.egress_global_timestamp);
            bit<32> value;
            x_register.read(value, (bit<32>) 0);
            if(value > 0){
                value= (value * (10 - SUB_FACTOR)) >> 4;
                x_register.write((bit<32>) 0,value);
            }

            x_register.read(value, (bit<32>) 1);
            if(value > 0){
                value= (value * (10 - SUB_FACTOR)) >> 4;
                x_register.write((bit<32>) 1,value);
            }

            x_register.read(value, (bit<32>) 2);
            if(value > 0){
                value= (value * (10 - SUB_FACTOR)) >> 4;
                x_register.write((bit<32>) 2,value);
            }

            x_register.read(value, (bit<32>) 3);
            if(value > 0){
                value= (value * (10 - SUB_FACTOR)) >> 4;
                x_register.write((bit<32>) 3,value);
            }

            x_register.read(value, (bit<32>) 4);
            if(value > 0){
                value= (value * (10 - SUB_FACTOR)) >> 4;
                x_register.write((bit<32>) 4,value);
            }

            x_register.read(value, (bit<32>) 5);
                if(value > 0){
                    value= (value * (10 - SUB_FACTOR)) >> 4;
                    x_register.write((bit<32>) 5,value);
            }
        }
        
    }
}

/*************************************************************************
*************   C H E C K S U M    C O M P U T A T I O N   **************
*************************************************************************/

control MyComputeChecksum(inout headers hdr, inout metadata meta) {
     apply {
        update_checksum(
            hdr.ipv4.isValid(),
            { hdr.ipv4.version,
              hdr.ipv4.ihl,
              hdr.ipv4.diffserv,
              hdr.ipv4.totalLen,
              hdr.ipv4.identification,
              hdr.ipv4.flags,
              hdr.ipv4.fragOffset,
              hdr.ipv4.ttl,
              hdr.ipv4.protocol,
              hdr.ipv4.srcAddr,
              hdr.ipv4.dstAddr },
            hdr.ipv4.hdrChecksum,
            HashAlgorithm.csum16);
    
    }
}


/*************************************************************************
***********************  D E P A R S E R  *******************************
*************************************************************************/

control MyDeparser(packet_out packet, in headers hdr) {

    apply{
        packet.emit(hdr.packet_in);
        packet.emit(hdr.ethernet);
        packet.emit(hdr.conga);
        packet.emit(hdr.ipv4);
        packet.emit(hdr.tcp);
        packet.emit(hdr.udp);
    }
}

/*************************************************************************
***********************  S W I T C H  *******************************
*************************************************************************/

V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
